import { createRouter, createWebHashHistory } from "vue-router";
import { useStore as useTagsStore } from "@/store/tags";
import { useStore as useUserStore } from "@/store/user";
import { useStore as useMenuStore } from "@/store/menu";
import { judgeAuth } from "@/auth/checkAuth";
import { $menuList } from "@/api/menu/menu";
import { $freeAdminNodeList } from "@/api/free/free";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import home from "./modules/home/home";
import whiteList from "@/config/whiteList";
import metaInterface from "./meta.interface";
import permission from "./modules/permission/permission";
import channelManagement from "./modules/channelManagement/channelManagement";
import statisticalManagement from "./modules/statisticalManagement/statisticalManagement";
import productManage from "./modules/productManage/productManage";
import systemConfiguration from "./modules/systemConfiguration/systemConfiguration";
import policys from "./modules/policys/policys";
import _ from "lodash";

const project_name = require("@/config/main").project_name;

const routes: Array<any> = [
  {
    path: "/",
    name: "index",
    component: () => import("@/views/index/index"),
    redirect: "/home",
    meta: {
      title: project_name || "中台",
    } as metaInterface,
    children: [
      home,
      productManage,
      channelManagement,
      permission,
      statisticalManagement,
      systemConfiguration,
      policys,
      {
        path: "/:pathMatch(.*)*",
        name: "404",
        component: () => import("@/views/index/404/404"),
        meta: {
          title: "404",
          hidden: true,
        } as metaInterface,
      },
      {
        path: "/403",
        name: "403",
        component: () => import("@/views/index/403/403"),
        meta: {
          title: "403",
          hidden: true,
        } as metaInterface,
      },
      {
        path: "/500",
        name: "500",
        component: () => import("@/views/index/500/500"),
        meta: {
          title: "500",
          hidden: true,
        } as metaInterface,
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/login"),
    meta: {
      title: "登录"
    } as metaInterface,
  },
  {
    path: "/changePassword",
    name: "changePassword",
    component: () => import("@/views/index/changePassword/changePassword"),
    meta: {
      title: "修改密码",
    } as metaInterface,
  },

];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 获取菜单列表
const getMenuList = () => {
  const menuStore = useMenuStore();
  return new Promise((resolve) => {
    $menuList({ status: "1" })
      .then((res: any) => {
        menuStore.setMenuList(res.data?.menu_list || []);
        menuStore.setAll(res?.data?.all || []);
        const menu_list = menuStore.state.menu_list || [];
        let flat_menu_list: any[] = [];
        const eachFlat = (arr: any[], arr2: any[]) => {
          arr.forEach((x: any) => {
            arr2.push(x);
            x?.childlist?.length > 0 && eachFlat(x.childlist, arr2);
          });
        };
        eachFlat(menu_list, flat_menu_list);
        // 处理菜单对应路由
        router.getRoutes().forEach((item: any) => {
          let idx = flat_menu_list.findIndex((x) => item.name === x.path);
          if (idx > -1) {
            item.meta.title = flat_menu_list?.[idx]?.menu_name || "";
            item.meta.auth = flat_menu_list?.[idx]?.perms || "";
            item.meta.hidden = Number(flat_menu_list?.[idx]?.visible)
              ? false
              : true;
            item.meta.isCache = flat_menu_list?.[idx]?.is_cache ? true : false;
            item.meta.disVisit = Number(flat_menu_list?.[idx]?.status)
              ? false
              : true;
            // 菜单项为目录，重定向到可用路由(未停用、显示、有权限)
            if (
              flat_menu_list?.[idx]?.menu_type === "M" &&
              flat_menu_list?.[idx]?.childlist?.some(
                (x: any) =>
                  Number(x.visible) &&
                  Number(x.status) &&
                  judgeAuth(x?.perms || "")
              )
            ) {
              item.redirect = {
                name: flat_menu_list?.[idx]?.childlist
                  .sort((a: any, b: any) => a.order_num - b.order_num)
                  .find(
                    (x: any) =>
                      Number(x.visible) &&
                      Number(x.status) &&
                      judgeAuth(x?.perms || "")
                  ).path,
              };
            }
          }
        });
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};

// 获取权限列表
const getAuthList = () => {
  const menuStore = useMenuStore();
  return new Promise((resolve) => {
    $freeAdminNodeList()
      .then((res: any) => {
        menuStore.setAuths(res?.data?.perms || []);
        resolve(true);
      })
      .catch(() => {
        resolve(false);
      });
  });
};
// 路由跳转前判断权限
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const userStore = useUserStore();
  const menuStore = useMenuStore();
  const token = userStore.token;
  if (token) {
    if (!userStore.isSuperAdmin) {
      next();
    } else {
      if (to.path === "/login") {
        next({ path: "/" });
        NProgress.done();
      } else {
        if (!menuStore.loaded) {
          const res1 = await getAuthList();
          const res2 = await getMenuList();
          res1 && menuStore.menuLoaded();
          res2 && menuStore.authLoaded(true);
          // 获取到菜单重定向
          if (res1 && res2) {
            next({ ...to, replace: true });
          } else {
            next();
          }
        } else {
          // 页面已停用
          if (to.meta.disVisit) {
            next("/404");
          }
          // 页面需权限但用户无该权限
          else if (!judgeAuth(to.meta?.auth as string)) {
            next("/403");
          } else {
            next();
          }
        }
      }
    }
  } else {
    if (whiteList?.includes?.(to.path)) {
      if (to.path === "/login") {
        menuStore.setAuths([]);
        menuStore.authLoaded(false);
        NProgress.done();
      }
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

// 路由跳转后添加标签
router.afterEach((to, from) => {
  NProgress.done();
  const tagsStore = useTagsStore();
  const { name, query, params, meta } = to;
  if (to.matched[0].name === "index") {
    if (!to.meta.affix) {
      tagsStore.addTag({
        name,
        query,
        params,
        meta,
      });
    }
    tagsStore.tagChange(name);
  }
  document.title = (to?.meta?.title as string) ?? "";
});

export default router;
